<template>
	<view class="app">
		<view class="example">
			<!-- 自定义表单校验 -->
			<uni-forms ref="customForm" :rules="customRules" :modelValue="baseFormData">
				<uni-forms-item label="用户名" required name="username">
					<uni-easyinput v-model="baseFormData.username" placeholder="请输入姓名" />
				</uni-forms-item>
				<uni-forms-item label="密码" required name="password">
					<uni-easyinput type="password" v-model="baseFormData.password" placeholder="请输入密码" />
				</uni-forms-item>
			</uni-forms>
			<button type="primary" @click="submit('customForm')">提交</button>


			<button type="primary" @click="submitzhuce('baseForm')" style="margin-top: 20rpx;">没有账号？ 点击去注册</button>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 基础表单数据
				baseFormData: {
					username: '',
					password: '',
				},
				// 自定义表单校验规则
				customRules: {
					username: {
						rules: [{
							required: true,
							errorMessage: '姓名不能为空'
						}]
					},
					password: {
						rules: [{
							required: true,
							errorMessage: '密码不能为空'
						}]
					}

				}
			}
		},
		methods: {
			submit(ref) {
				let _this = this;
				this.$refs[ref].validate().then(res => {
					console.log('success', res);
					console.log('success', _this.baseFormData);

					uni.showLoading({
						title: "登录中"
					})
					uni.request({
						url: "http://localhost:8000/api/login",
						method: "GET",
						data: {
							username: _this.baseFormData.username,
							password: _this.baseFormData.password
						},
						success(res) {
							if (res.data.code == 200) {
								console.log('res.data.data', res.data.data)
								console.log('res.data', res.data.message)
								uni.setStorageSync("username", _this.baseFormData.username)
								uni.setStorageSync("img", res.data.data[0].avatar)
								uni.setStorageSync('token', 200)
								uni.showToast({
									title: "登录成功"
								})

								setTimeout(() => {
									// uni.switchTab({
									// 	url:"/pages/my/my"
									// })
									uni.navigateBack()
								}, 2000)

							} else {
								console.log('res.data', res.data.message)
								uni.showToast({
									title: "登录失败",
									icon: 'error'
								})
							}
							uni.hideLoading()
						},
						fail(err) {
							console.log('err', err)
						}
					})
				}).catch(err => {
					console.log('err', err);
				})
			},
			// 注册
			submitzhuce() {
				console.log('dfddd')
				uni.navigateTo({
					url: "/pages/register/register"
				})

			}
		}
	}
</script>

<style>
	.app {
		width: 100%;
		height: 100vh;
		/* background: linear-gradient(180deg, rgb(63, 47, 130) 0%, rgb(177, 111, 155) 100%); */
		/* animation: 1s running test linear infinite; */
	}
</style>